import axios from 'axios'
import {Modal} from 'antd'
import qs from 'querystring'
import EventEmitter from 'events'
import moment from 'moment'
import 'moment/locale/zh-cn'
import nodeUrl from 'url'
import * as R from 'ramda'
import {emoji} from './emoji'
import xss from 'xss'

moment.locale('zh-cn')

export {moment}

const defaultAxiosConf = {
  timeout: 10000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  baseURL: '/'
}

export function http(params = {}, fn) {
  if (typeof fn === 'function') fn(true)
  return axios({...defaultAxiosConf, ...params}).then(res => {
    if (typeof fn === 'function') fn(false)
    const {result, mes} = res.data
    if (result === 0) {
      throw new Error(mes)
    } else {
      return res.data
    }
  }).catch(err => {
    if (typeof fn === 'function') fn(false)
    console.error(err)
    throw err
  })
}

export const post = (url, data, cb) => {
  data = qs.stringify(data)
  return http({data, url, method: 'post'}, cb)
}

export const get = (url, data = {}, cb) => {
  R.compose(
    (o) => {
      const exitSearch = queryParse(o.search)
      const search = qs.stringify(
        Object.assign({}, exitSearch, data)
      )
      url = nodeUrl.resolve(url, `?${search}`)
    },
    (str) => nodeUrl.parse(str)
  )(url)
  return http({data, url, method: 'get'}, cb)
}

export function confirm(content) {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title: '提示',
      content,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        resolve()
      },
      onCancel: () => {
        reject()
      }
    })
  })
}

export function upload(url, form, params, fn, cb) {
  if (params) {
    url = `${url}?${qs.stringify(params)}`
  }
  return http({
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    url: url,
    data: form,
    onUploadProgress(processEvent) {
      // 原生进度事件
      const percent = processEvent.loaded / processEvent.total * 100
      if (typeof cb === 'function') cb(percent)
    }
  }, fn)
}

export function autoImg(e) {
  let dom = e.target
  let parent = dom.parentElement
  let p = parent.clientHeight / parent.clientWidth
  let m = dom.clientHeight / dom.clientWidth
  if (p > m) {
    dom.style.height = '100%'
    dom.style.width = 'auto'
    dom.style.marginLeft = '-' + (dom.clientWidth * parent.clientHeight / dom.clientHeight - parent.clientWidth) / 2 + 'px'
  } else {
    dom.style.height = 'auto'
    dom.style.width = '100%'
    dom.style.marginTop = '-' + (dom.clientHeight * parent.clientWidth / dom.clientWidth - parent.clientHeight) / 2 + 'px'
  }
}

export function sleep(time = 500) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}

export function renderTitle(tit) {
  document.title = tit || 'Knight TV'
}

export function debounce(func, delay = 300) {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func(...args)
    }, delay)
  }
}

export async function logout(cb) {
  Modal.confirm({
    title: '确定退出？',
    async onOk() {
      let res = await http({
        method: 'post',
        url: '/api/users/logout'
      })
      if (res.result === 1) {
        if (typeof cb === 'function') cb()
        window.location.reload()
      }
    }
  })
}

class MyEvent extends EventEmitter {
}

export const eventEmitter = new MyEvent()

export function fromNow(d) {
  const mt = moment(d)
  if (Math.abs(mt.diff()) > 24 * 60 * 60 * 1000) {
    return mt.format('YYYY-MM-DD HH:mm')
  } else {
    return mt.fromNow(false)
  }
}

export function notLogin() {
  Modal.confirm({
    title: '提示',
    content: '您还未登陆，是否前往登陆？',
    onOk() {
      window.location.href = `/login?redirect=${encodeURIComponent(window.location.href)}`
    }
  })
}

// 解析query
export function queryParse(str) {
  if (typeof str === 'undefined') str = window.location.href
  if (typeof str !== 'string') return {}
  const search = nodeUrl.parse(str).search
  if (search) {
    return qs.parse(search.substr(1))
  } else {
    return {}
  }
}

export function dropRepeat(fn) {
  return function (arr) {
    for (let i = 0; i < arr.length; i++) {
      const index = arr.findIndex(item => fn(item) === fn(arr[i]))
      if (index > -1 && index < i) {
        arr.splice(i, 1)
        i--
      }
    }
    return arr
  }
}

const myXss = new xss.FilterXSS({
  onTagAttr(tag, name, value, isWhiteAttr) {
    // tag是当前的标签名称，比如<a>标签，则tag的值是'a'
    // name是当前属性的名称，比如href="#"，则name的值是'href'
    // value是当前属性的值，比如href="#"，则value的值是'#'
    // isWhiteAttr是否为白名单上的属性
    // 如果返回一个字符串，则当前属性值将被替换为该字符串
    // 如果不返回任何值，则使用默认的处理方法
    //   在白名单上：  调用safeAttrValue来过滤属性值，并输出该属性，详见下文
    //   不在白名单上：通过onIgnoreTagAttr指定，详见下文
    if (name === 'class') return `${name}="${value}"`
  }
})

export function filterText(str = '') {
  emoji.forEach((item) => {
    const alt = item.alt.replace(/(\[)/g, '\\$1')
    str = str.replace(new RegExp(alt, 'g'), `<img class="emoji" style="width: 30px;" src="${item.src}" title="${item.alt}" alt="${item.alt}" />`)
  })
  str = myXss.process(str)
  return str
}
